package com.bmth.alise.utils;

import java.util.List;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

import com.bmth.alise.conf.Configuration;

public class MQSender {
	private static MQSender instance = new MQSender();

	public static MQSender getInstance() {
		return instance;
	}

	Connection connection;
	Session session;

	private MQSender() {
		try {
			String MQUrl = Configuration.getProperty("MQUrl");
			connection = new ActiveMQConnectionFactory(MQUrl).createConnection();
			connection.start();
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public void send(String queueName, String message) {
		try {
			Destination sendQueue = session.createQueue(queueName);
			MessageProducer sender = session.createProducer(sendQueue);
			TextMessage outMessage = session.createTextMessage();
			outMessage.setText(message);
			sender.send(outMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void send(String queueName, List<String> messages) {
		for (String message : messages) {
			System.out.println(message);
			send(queueName, message);
		}
	}

	public void closeSession() {

		if (session != null) {
			try {
				session.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	public void closeConnection() {
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void closeResourses() {
		closeSession();
		closeConnection();
	}

	public void initConnectionAndSession() {
		instance = new MQSender();
	}
}
